package org.tea.inventory.admin.web.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.tea.inventory.admin.annotation.LoginAdmin;
import org.tea.inventory.admin.service.AdminTokenManager;
import org.tea.inventory.admin.util.bcrypt.BCryptPasswordEncoder;
import org.tea.inventory.base.util.ResponseUtil;
import org.tea.inventory.base.util.excel.ExportExcel;
import org.tea.inventory.db.domain.Admin;
import org.tea.inventory.db.domain.AlumniUser;
import org.tea.inventory.db.service.AdminService;
import org.tea.inventory.db.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.tea.inventory.domain.tea.CustomerSmall;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "系统管理-用户管理控制器")
@RestController
@RequestMapping("/admin/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private UserService userService;
    /**
     * 获取登录用户信息
     * @param token 用户在认证中心成功登录后，认证中心生成一个包含用户身份信息的Token，并将其发送给用户访问的系统
     * @return
     */
    @GetMapping("/info")
    public Object info(String token){
        Integer adminId = AdminTokenManager.getUserId(token);
        if(adminId == null){
            return ResponseUtil.badArgumentValue();
        }
        Admin admin = adminService.findById(adminId);
        if(admin == null){
            return ResponseUtil.badArgumentValue();
        }

        Map<String, Object> data = new HashMap<>();
        data.put("name", admin.getUsername());
        data.put("avatar", admin.getAvatar());

        // 目前roles不支持，这里简单设置admin
        List<String> roles = new ArrayList<>();
        roles.add("admin");
        data.put("roles", roles);
        data.put("introduction", "admin introduction");
        return ResponseUtil.ok(data);
    }
    /**
     * 查询用户信息列表
     * @param adminId
     * @param username
     * @param nickname
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    @GetMapping("/list")
    public Object list(@LoginAdmin Integer adminId,
                       String username,
                       String nickname,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                       String sort, String order){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        List<Admin> adminList = adminService.querySelective(username, page, limit, sort, order, nickname);
        int total = adminService.countSelective(username, page, limit, sort, order, nickname);
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", adminList);

        return ResponseUtil.ok(data);
    }

    /**
     * 导出用户信息列表
     */
    @GetMapping("/export")
    @ApiOperation(value = "导出用户信息列表")
    public void export(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        String title = "用户信息列表";
        String header = "用户ID,用户名称,用户昵称,用户头像";
        String column = "id,username,nickname,avatar";
        map.put("biaoti", title);
        map.put("header", header);
        map.put("column", column);
        try {
            List<Admin> list = adminService.querySelective();
            List<Map> listMap = JSONArray.parseArray(JSON.toJSONString(list), Map.class);
            ExportExcel.export(request, response, listMap, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建用户
     * @param adminId
     * @param admin 用户信息
     * @return
     */
    @PostMapping("/create")
    public Object create(@LoginAdmin Integer adminId, @RequestBody Admin admin){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        //String rawPassword = admin.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //String encodedPassword = encoder.encode(rawPassword);
        //admin.setPassword(encodedPassword);
        admin.setPassword(encoder.encode(admin.getPassword()));

        adminService.add(admin);
        return ResponseUtil.ok(admin);
    }

    @GetMapping("/getUser")
    public Object getUser(@LoginAdmin Integer adminId, String userName) {
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        if(userName == null){
            return ResponseUtil.badArgument();
        }
        Boolean flag = adminService.findUserName(userName);
        return ResponseUtil.ok(flag);
    }

    @GetMapping("/read")
    public Object read(@LoginAdmin Integer adminId, Integer id){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        if(id == null){
            return ResponseUtil.badArgument();
        }

        Admin admin = adminService.findById(id);
        return ResponseUtil.ok(admin);
    }
    /**
     * 更新用户信息
     * @param adminId
     * @param admin 用户信息
     * @return
     */
    @PostMapping("/update")
    public Object update(@LoginAdmin Integer adminId, @RequestBody Admin admin){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        Integer anotherAdminId = admin.getId();
        if(anotherAdminId.intValue() == 1 && adminId.intValue() != 1){//只有超管本人能修改
            return ResponseUtil.fail(403, "超级管理员不能修改");
        }
        
        //String rawPassword = admin.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //String encodedPassword = encoder.encode(rawPassword);
        //admin.setPassword(encodedPassword);
        admin.setPassword(encoder.encode(admin.getPassword()));
        
        adminService.updateById(admin);

        return ResponseUtil.ok(admin);
    }

    @PostMapping("/delete")
    public Object delete(@LoginAdmin Integer adminId, @RequestBody Admin admin){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        Integer anotherAdminId = admin.getId();
        if(anotherAdminId.intValue() == 1){
            return ResponseUtil.fail(403, "超级管理员不能删除");
        }
        adminService.deleteById(anotherAdminId);
        return ResponseUtil.ok();
    }

    @GetMapping("/getWxUserId")
    public Object getWxUserId(@LoginAdmin Integer adminId, String phone) {

        int userId = 0;

        if(StringUtils.isNotBlank(phone)) {
            AlumniUser alumniUser = new AlumniUser();
            alumniUser.setPhone(phone);
            PageInfo<AlumniUser> pageInfo = userService.querySelective(alumniUser, 1, 10, null, null);

            if (pageInfo.getList().size() == 1) {
                userId = pageInfo.getList().get(0).getId();
            }
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("userId", userId);
        return ResponseUtil.ok(data);
    }


    public Object uploadAvatar(@RequestParam("file") MultipartFile file){

        System.out.print(""+file.getSize());


        return ResponseUtil.ok();
    }	
}
